<template>
  <div class="contract-container">
    <t-card class="list-card-container" :bordered="false">
      <template #title>合同管理</template>
      <template #actions>
        <t-row justify="space-between" align="middle">
          <t-col>
            <t-button @click="handleShowSearch">搜索</t-button>
          </t-col>
          <t-col>
            <t-button @click="handleAdd">新增合同</t-button>
          </t-col>
        </t-row>
      </template>
      <contract-list
        ref="listRef"
        :loading="loading"
        :data="contractList"
        :pagination="pagination"
        @page-change="onPageChange"
        @edit="handleEdit"
        @delete="handleDelete"
      />
    </t-card>

    <contract-form
      v-model:visible="formVisible"
      :form-data="currentContract"
      :type="formType"
      @success="onFormSuccess"
      @cancel="onFormCancel"
    />

    <contract-dialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :content="dialogContent"
      @confirm="onDialogConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import ContractList from './components/ContractList.vue';
import ContractForm from './components/ContractForm.vue';
import ContractDialog from './components/ContractDialog.vue';
import { getContractList, deleteContract } from '@/api/contract';
import type { ContractInfo } from '@/api/contract';

const loading = ref(false);
const contractList = ref<ContractInfo[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const formVisible = ref(false);
const formType = ref<'add' | 'edit'>('add');
const currentContract = ref<Partial<ContractInfo>>({});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogContent = ref('');
const listRef = ref();

// 获取合同列表
const fetchContractList = async () => {
  loading.value = true;
  try {
    const res = await getContractList({
      current: pagination.value.current,
      pageSize: pagination.value.pageSize
    });
    console.log('获取合同列表成功:', res);
    if ( res.records) {
      contractList.value = res.records || [];
      pagination.value.total = res.total || 0;
    } else {
      MessagePlugin.error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取合同列表失败:', error);
    MessagePlugin.error('获取合同列表失败');
  } finally {
    loading.value = false;
  }
};

// 新增合同
const handleAdd = () => {
  formType.value = 'add';
  currentContract.value = {};
  formVisible.value = true;
};

// 编辑合同
const handleEdit = (contract: ContractInfo) => {
  formType.value = 'edit';
  currentContract.value = { ...contract };
  formVisible.value = true;
};

// 删除合同
const handleDelete = (contract: ContractInfo) => {
  dialogTitle.value = '删除确认';
  dialogContent.value = `确定要删除合同"${contract.name}"吗？`;
  currentContract.value = contract;
  dialogVisible.value = true;
};

// 确认删除
const onDialogConfirm = async () => {
  try {
    if (!currentContract.value.id) {
      MessagePlugin.error('合同ID不存在');
      return;
    }
    await deleteContract(currentContract.value.id);
    MessagePlugin.success('删除成功');
    await fetchContractList();
  } catch (error) {
    console.error('删除失败:', error);
    MessagePlugin.error('删除失败');
  } finally {
    dialogVisible.value = false;
  }
};

// 表单提交成功
const onFormSuccess = async () => {
  formVisible.value = false;
  await fetchContractList();
};

// 取消表单
const onFormCancel = () => {
  formVisible.value = false;
};

// 分页变化
const onPageChange = async (pageInfo: { current: number; pageSize: number }) => {
  pagination.value.current = pageInfo.current;
  pagination.value.pageSize = pageInfo.pageSize;
  await fetchContractList();
};

// 显示搜索表单
const handleShowSearch = () => {
  // TODO: 实现搜索功能
  MessagePlugin.info('搜索功能开发中');
};

onMounted(() => {
  fetchContractList();
});
</script>

<style lang="less" scoped>
.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}
</style>
